package com.kit.common.utils;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 灯杆广告接口接入工具类
 *
 * @author zhangxin
 * @date 2024-05-15 21：42
 */
public class DgApiUtil {

    public static final String USERNAME = "yzs859816616";
    public static final String PASSWORD = "Aa859816616";


    /**
     * GET方式调用接口
     * @param url   接口地址
     * @param paramMap  参数
     * @return  返回调用结果
     */
    public static Map<String, Object> doGet(String url, Map<String, String> paramMap) {
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("code", 500);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.US_ASCII)));
        try {
            Response response = doGet(url, paramMap, headers);
            respMap.put("code", response.code());
            if (response.code() == 200) respMap.put("data", response.body().string());
            // 调用成功日志
        } catch (IOException e) {
            // throw new RuntimeException(e);
            // TODO 记录失败日志
        }
        return respMap;
    }

    /**
     * 以get方式调用第三方接口
     * @param url   请求地址
     * @param paramMap   请求参数
     * @param heardMap   请求头
     * @return 返回调用结果
     */
    public static Response doGet(String url, Map<String, String> paramMap, Map<String, String> heardMap) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder requestbuilder = new Request.Builder()
                .get();//默认就是GET请求，可以不写

        //增加参数
        StringBuilder urlbuilder = new StringBuilder(url);
        if (Objects.nonNull(paramMap)) {
            urlbuilder.append("?");
            paramMap.forEach((key, value) -> {
                try {
                    urlbuilder.append(URLEncoder.encode(key, "utf-8")).append("=").append(URLEncoder.encode(value, "utf-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
            urlbuilder.deleteCharAt(urlbuilder.length() - 1);
        }
        //增加请求头
        Request.Builder heardBuilder = requestbuilder.url(urlbuilder.toString());
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            heardBuilder.addHeader(stringObjectEntry.getKey(),stringObjectEntry.getValue());
        }

        Request request = heardBuilder.build();
        return okHttpClient.newCall(request).execute();
    }


    /**
     * post调用接口
     * @param url   接口地址
     * @param paramMap  参数
     * @return  返回调用结果
     */
    public static Map<String, Object> doPost(String url, Map<String, Object> paramMap) {
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("code", 500);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.US_ASCII)));
        try {
            Response response = doPost(url, paramMap, headers);
            respMap.put("code", response.code());
            if (response.code() == 200) respMap.put("data", response.body().string());
            // 调用成功日志
        } catch (IOException e) {
            // throw new RuntimeException(e);
            // TODO 记录失败日志
        }
        return respMap;
    }

    /**
     * post请求接口
     * @param url   接口地址
     * @param paramMap  参数
     * @param heardMap  请求头
     * @return  返回调用结果
     * @throws IOException
     */
    public static Response doPost(String url, Map<String, Object> paramMap,Map<String,String> heardMap) throws IOException {
        FormBody.Builder formBody = new FormBody.Builder();
        if (Objects.nonNull(paramMap)) {
            paramMap.forEach((x, y) -> formBody.add(x, (String) y));
        }
        RequestBody requestBody = formBody.build();
        Request.Builder requestbuilder = new Request.Builder()
                .url(url)
                .post(requestBody);
        //增加请求头
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            requestbuilder.addHeader(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }

        Request request = requestbuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        return okHttpClient.newCall(request).execute();
    }

    /**
     * 文件上传接口调用
     *
     * @param url   接口地址
     * @param paramMap  文件外参数
     * @param file  文件
     * @return  返回调用结果
     */
    public static Map<String, Object> upLoadFile(final String url, final Map<String, Object> paramMap, File file) {
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("code", 500);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.US_ASCII)));
        try {
            Response response = upLoadFile(url, paramMap, headers, file);
            respMap.put("code", response.code());
            if (response.code() == 200) respMap.put("data", response.body().string());
            // 调用成功日志
        } catch (IOException e) {
            // throw new RuntimeException(e);
            // TODO 记录失败日志
        }
        return respMap;
    }

    /**
     * 文件上传
     *
     * @param url   文件上传地址
     * @param paramMap  参数
     * @param heardMap  请求头
     * @param file  文件
     * @throws IOException
     */
    public static Response upLoadFile(final String url, final Map<String, Object> paramMap, final Map<String,String> heardMap, File file) throws IOException {
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart("file", file.getName(), body);
        }
        // 设置参数
        if (paramMap != null) {
            // map 里面是请求中所需要的 key 和 value
            for (Map.Entry entry : paramMap.entrySet()) {
                requestBody.addFormDataPart(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }
        Request.Builder requestbuilder = new Request.Builder()
                .url(url)
                .post(requestBody.build());
        //增加请求头
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            requestbuilder.addHeader(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }
        Request request = requestbuilder.build();
//        Request request = new Request.Builder().url(url).post(requestBody.build()).build();
        // readTimeout("请求超时时间" , 时间单位);
        return client.newCall(request).execute();
    }

    public static void main(String[] args) throws IOException {
        /*Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString("yzs859816616:Aa859816616".getBytes(StandardCharsets.US_ASCII)));

        Map<String, Object> params = new HashMap<>();
        params.put("terminalIds", "12380380");
        DgApiUtil.doGet("http://www.colorlightcloud.com/wp-json/wp/v2/leds/terminals", params, headers);*/


        /*Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString("yzs859816616:Aa859816616".getBytes(StandardCharsets.US_ASCII)));

        Map<String, Object> params = new HashMap<>();
        params.put("terminalIds", "12380380");
        DgApiUtil.doPost("http://www.colorlightcloud.com/wp-json/wp/v2/leds/terminals", params, headers);*/

//        File file = new File("F:\\UI图片\\Cards.png");
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Authorization", "Basic "+ Base64.getEncoder().encodeToString("yzs859816616:Aa859816616".getBytes(StandardCharsets.US_ASCII)));
//        DgApiUtil.upLoadFile("https://www.colorlightcloud.com/wp-json/wp/v2/media", null, file);
        Map<String, String> params = new HashMap<>();
        params.put("page", "1");
        params.put("per_page", "1");
        params.put("flag", "filter");
        Map<String, Object> response = DgApiUtil.doGet("https://www.colorlightcloud.com/wp-json/wp/v2/media" , params);
        System.out.println(response.toString());
    }
}
